//
//  NvDraftViewController.m
//  NvSellerShow
//
//  Created by Meicam on 2017/3/20.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvDraftViewController.h"
#import "NvProcedureDlgViewController.h"
#import "NvDraftManager.h"

@interface NvDraftViewController ()

@end

@implementation NvDraftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.editing = NO;
//    self.bottomAreaHConstraint.constant = 0;
    self.bottomView.hidden = YES;
    self.draftArray = [NSMutableArray array];
    self.selectedArray = [NSMutableArray array];
    
    [self initDraftModel];
    [self updateEditBtnEnableState];
    [self initNavigationBarView ];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning  ];
    // Dispose of any resources that can be recreated.
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    self.tableView.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editBtn.frame = CGRectMake(self.view.width_LL-40, 0, 40, 44);
    [self.editBtn setTitle:@"管理" forState:UIControlStateNormal];
    [self.editBtn setTitleColor:UIColorHexRGB(@"#3F80FF") forState:UIControlStateNormal];
    [self.editBtn addTarget:self action:@selector(editBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.editBtn];
    
    self.title = @"草稿箱";
}

- (void)updateDraftModel {
    [self.draftArray removeAllObjects];
    [self initDraftModel];
    [self updateEditBtnEnableState];
    [self.tableView reloadData];
}

- (void)initDraftModel {
    NSArray *draftDicArray = [NvDraftManager getAllDrafts];
    NvDraftModel *draftModel;
    for(NSDictionary *draftDic in draftDicArray){
        draftModel = [[NvDraftModel alloc]initWithDraftDictianary:draftDic];
        [self.draftArray addObject:draftModel];
    }
}

- (void)updateSelectAllBtnState {
    if (self.draftArray.count == 0) {
        [self.selectAllBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    if(self.selectedArray.count != 0 && self.selectedArray.count == self.draftArray.count){
        [self.selectAllBtn setTitle:@"取消全选" forState:UIControlStateNormal];
    }
    else {
        [self.selectAllBtn setTitle:@"全选" forState:UIControlStateNormal];
    }
}

- (void)updateDeleteButtonState {
    if(self.selectedArray.count > 0)
        self.deleteBtn.enabled = YES;
    else
        self.deleteBtn.enabled = NO;
}

- (void)doDeleteDraftWorks {
    [Utils showConfirmAlertWithTitle:@"删除提示" message:@"是否删除选中的草稿" yesTitle:@"确定" yesAction:^{
        NSMutableArray *draftIdArray = [NSMutableArray array];
        NSMutableArray *indexPathsArray = [NSMutableArray array];
        for(NvDraftModel *draftModel in self.selectedArray) {
            NSInteger index = [self.draftArray indexOfObject:draftModel];
            if(index != NSNotFound) {
                NSIndexPath * indexPath = [NSIndexPath indexPathForRow:index inSection:0];
                [indexPathsArray addObject:indexPath];
            }
            [draftIdArray addObject:draftModel.draftId];
        }
        [self.draftArray removeObjectsInArray:self.selectedArray];
        [NvDraftManager deleteDraftAtIds:draftIdArray];
        [self.selectedArray removeAllObjects];
        [self.tableView deleteRowsAtIndexPaths:indexPathsArray withRowAnimation:UITableViewRowAnimationAutomatic];
        if(self.isEditing) {
            [self changeEditBtnState];
        }
        [self updateEditBtnEnableState];
    }];
}

- (void)updateEditBtnEnableState {
    if(self.draftArray.count > 0){
        self.editBtn.enabled = YES;
    }
    else {
        self.editBtn.enabled = NO;
    }
}
- (void)changeEditBtnState {
    
    self.isEditing = !self.isEditing;
    if (self.isEditing) {
        self.bottomView.hidden = NO;
        
        [self.editBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self updateSelectAllBtnState];
        [self updateDeleteButtonState];
    
    }else{
        self.bottomView.hidden = YES;
        [self.editBtn setTitle:@"管理" forState:UIControlStateNormal];
    
        [self.selectedArray removeAllObjects];

    }
    [self.tableView reloadData];
}

#pragma mark - Implement NvDraftTableViewCellDelegate
- (void)draftTableViewCell:(NvDraftTableViewCell *)cell openDraftModel:(NvDraftModel *)draftModel {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"ProcedureDlg" bundle:myBundle];
    
    NvProcedureDlgViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvProcedureDlgViewController"];
    modalView.draftDictionary = draftModel.draftDic;
    modalView.delegate = self;
    [self.navigationController pushViewController:modalView animated:YES];
}

- (void)draftTableViewCell:(NvDraftTableViewCell *)cell updateCheckState:(BOOL)isChecked withDraftModel:(NvDraftModel *)draftModel {
    if(isChecked)
        [self.selectedArray addObject:draftModel];
    else
        [self.selectedArray removeObject:draftModel];
    [self updateSelectAllBtnState];
    [self updateDeleteButtonState];
    
}


#pragma mark - Implement draftTableView Cell Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.draftArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *draftCellIdentifier = @"NvDraftTableViewCell";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    NvDraftTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:draftCellIdentifier];
    if(cell == nil){
        cell = [[myBundle loadNibNamed:draftCellIdentifier owner:nil options:nil] firstObject];
    }
    NvDraftModel *model = self.draftArray[indexPath.row];
    
    BOOL isSelected = NO;
    if([self.selectedArray indexOfObject:model] != NSNotFound)
        isSelected = YES;
    [cell setEditingMode:self.isEditing];
    [cell fillDraftModel:model];
    [cell setCheckedState:isSelected];
    cell.delegate = self;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NvDraftModel *model = self.draftArray[indexPath.row];
    [self.selectedArray addObject:model];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除确认" message:@"确定要删除选中的草稿吗" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self.selectedArray removeAllObjects];
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action){
        [self doDeleteDraftWorks];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSString*)tableView:(UITableView*)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath*)indexPath {
    return @"删除";
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.isEditing)
        return NO;
    return YES;
}


#pragma mark - NvProcedureDlgViewControllerDelegate
- (void)nvProcedureDlgViewControllerPoped:(NvProcedureDlgViewController *)controller{
    [self updateDraftModel];
}

#pragma mark - Button response

- (void)editBtnPressed:(id)sender {

    [self changeEditBtnState];
}

- (void)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)selectAllBtnPressed:(id)sender {
    
    if(self.selectedArray.count == self.draftArray.count) {
        [self.selectedArray removeAllObjects];
    }
    else {
        self.selectedArray = self.draftArray.mutableCopy;
    }
    [self updateSelectAllBtnState];
    [self updateDeleteButtonState];
    [self.tableView reloadData];
}

- (IBAction)deleteBtnPressed:(id)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除确认" message:@"确定要删除选中的草稿吗" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action){
        [self doDeleteDraftWorks];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
@end
